<template>
  <div class="infinite-scroll" ref="scrollContainerRef">
    <slot></slot>
    <div v-if="loading" class="loading">Loading...</div>
  </div>
</template>

<script setup lang="ts">

type InfiniteScrollProps = {
  // list: string[];
  loading:boolean;
}

const props = withDefaults(defineProps<InfiniteScrollProps>(),{
  loading:true
})
const emit = defineEmits<{
  (e:'load'):void
}>()
const scrollContainerRef = ref<HTMLElement>()

const handleScroll = () => {
  const scrollContainer = scrollContainerRef.value
  const scrollHeight = scrollContainer?.scrollHeight || 0
  const scrollTop = scrollContainer?.scrollTop || 0
  const clientHeight = scrollContainer?.clientHeight || 0

  if (scrollTop + clientHeight >= scrollHeight - 20 && !props.loading) {
    emit('load')
  }
}

onMounted(() => {
  const scrollContainer = scrollContainerRef.value
  scrollContainer?.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  const scrollContainer = scrollContainerRef.value
  scrollContainer?.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.infinite-scroll {
  height: 300px;
  overflow-y: auto;
}
.loading {
  text-align: center;
  margin-top: 10px;
  font-size: 14px;
  color: gray;
}
</style>
